package cn.cxyxj.code_resource_prod.code_resource.config;


import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义 Access 表达式进行权限验证
 *
 * @author cxyxj
 */
@Service
public class CustomizeAccessDecisionConfig {


    /**
     * 是否具有权限
     * @param request：请求信息
     * @param authentication：身份验证对象
     * @return true：具有 false：不具有
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        boolean hasPermission = false;
        Object principal = authentication.getPrincipal();
        // 进入到这里的逻辑，需要是已登录的身份验证对象，如果未登录，直接拒绝
        if (principal instanceof String && "anonymousUser".equals(principal)) {
            return false;
        }
        String requestUrl = request.getServletPath();
        PathMatcher matcher = new AntPathMatcher();
//        if (principal instanceof SysUserDetails) {
//            SysUserDetails sysUserDetails = (SysUserDetails) principal;
//            SysUser sysUser = sysUserDetails.getSysUser();
//            // 从redis中获得当前用户的权限，匹配当前请求是否有权限
//            Set<Object> redisSetUrl = RedisUtil.sGet(sysUser.getAccount() + ":" + sysUser.getId());
//            assert redisSetUrl != null;
//            Set<String> collect = redisSetUrl.stream().map(String::valueOf).collect(Collectors.toSet());
//            hasPermission = collect.stream().anyMatch(u -> matcher.match(u, requestUrl));
//        }
        return hasPermission;
    }
}
